package org.springblade.tms.module.gps.base;

import cn.hutool.http.Method;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springblade.common.utils.EnumUtils;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.system.feign.IDictBizClient;
import org.springblade.tms.global.constant.DictCodeConstant;
import org.springblade.tms.global.enums.GpsCarColorEnum;
import org.springblade.tms.global.exception.CommonException;
import org.springblade.tms.global.utils.HttpUtils;
import org.springblade.tms.module.gps.dto.*;
import org.springblade.tms.module.transportorder.entity.TMTransportOrder;
import org.springblade.tms.module.transportorder.service.ITransportOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedHashMap;
import java.util.Optional;

import static org.springblade.common.constant.TenantConstant.DEFAULT_TENANT_ID;
import static org.springblade.tms.global.constant.DictCodeConstant.GPS_SAVE_AND_ORDER;

/**
 * @projectName: BladeX
 * @package: org.springblade.tms.module.gps.base
 * @className: GPSRequestService
 * @author: yr
 * @description: gps请求服务
 * @date: 2022/4/29 17:01
 */
@Service
@Transactional
@Slf4j
@AllArgsConstructor
public class GPSRequestService {

    private final IDictBizClient dictClient;

    private final ITransportOrderService transportOrderService;

    /**
     * @param waybillSynchronizationDTO:
     * @return void
     * @author yr
     * @description 运单同步
     * @date 2022/5/5 9:31
     */
    public void waybillSynchronization(WaybillSynchronizationDTO waybillSynchronizationDTO) {
        TMTransportOrder tmTransportOrder = transportOrderService.lambdaQuery().eq(TMTransportOrder::getTransportNo, waybillSynchronizationDTO.getTransportNo()).one();
        if (tmTransportOrder != null) {
            String pushTag = tmTransportOrder.getPushTag();
            if (pushTag.equals("0")) {
                return;
            }
        }
        Optional<GpsCarColorEnum> enumByDesc = EnumUtils.getEnumByDesc(GpsCarColorEnum.class, waybillSynchronizationDTO.getGentlyBillVehicle().getCarColor());
        if (enumByDesc.isPresent()) {
            waybillSynchronizationDTO.getGentlyBillVehicle().setCarColor(enumByDesc.get().value());
        } else {
            waybillSynchronizationDTO.getGentlyBillVehicle().setCarColor(GpsCarColorEnum.其它.value());
        }
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        String url = dictClient.getValue(DictCodeConstant.THIRD_INTERFACE, GPS_SAVE_AND_ORDER, DEFAULT_TENANT_ID).getData();
        if (Strings.isBlank(url)) {
            CommonException.throwCommonException("未维护三方接口");
        }
        String body = JSON.toJSONString(waybillSynchronizationDTO, config);
        body = JSONUtil.toJsonPrettyStr(JsonUtil.parse(body, Object.class));
        String response = HttpUtils.gpsTask(url, Method.POST, new LinkedHashMap<>(), null, null, body, url);
        log.info(response);
        GPSData gpsData = JSONUtil.toBean(response, GPSData.class);
        if (!gpsData.getStatus().equals(20000)) {
            CommonException.throwCommonException(gpsData.getMsg());
        }
    }

    /**
     * @param gpsWaybillStatusChangeDTO:
     * @return void
     * @author yr
     * @description 运单状态变更
     * @date 2022/5/5 9:31
     */
    public void waybillStatusChange(GPSWaybillStatusChangeDTO gpsWaybillStatusChangeDTO) {
        TMTransportOrder tmTransportOrder = transportOrderService.lambdaQuery().eq(TMTransportOrder::getTransportNo, gpsWaybillStatusChangeDTO.getConsigNo()).one();
        if (tmTransportOrder != null) {
            String pushTag = tmTransportOrder.getPushTag();
            if (pushTag.equals("0")) {
                return;
            }
        }
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        String url = dictClient.getValue(DictCodeConstant.THIRD_INTERFACE, DictCodeConstant.UPDATE_STATUS, DEFAULT_TENANT_ID).getData();
        if (Strings.isBlank(url)) {
            CommonException.throwCommonException("未维护三方接口");
        }
        String body = JSON.toJSONString(gpsWaybillStatusChangeDTO, config);
        body = JSONUtil.toJsonPrettyStr(JsonUtil.parse(body, Object.class));
        String response = HttpUtils.gpsTask(url, Method.POST, new LinkedHashMap<>(), null, null, body, url);
        log.info(response);
        GPSData gpsData = JSONUtil.toBean(response, GPSData.class);
        if (gpsWaybillStatusChangeDTO.getStatus().equals("2")) {
            return;
        }
        if (!gpsData.getStatus().equals(20000)) {
            CommonException.throwCommonException(gpsData.getMsg());
        }
    }

    /**
     * @param gpsWaybillModificationDTO:
     * @return void
     * @author yr
     * @description 运单修改
     * @date 2022/5/5 9:31
     */
    public void waybillModification(GPSWaybillModificationDTO gpsWaybillModificationDTO) {
        TMTransportOrder tmTransportOrder = transportOrderService.lambdaQuery().eq(TMTransportOrder::getTransportNo, gpsWaybillModificationDTO.getTransportNo()).one();
        if (tmTransportOrder != null) {
            String pushTag = tmTransportOrder.getPushTag();
            if (pushTag.equals("0")) {
                return;
            }
        }
        gpsWaybillModificationDTO.setCarColor(EnumUtils.getEnumByDesc(GpsCarColorEnum.class, gpsWaybillModificationDTO.getCarColor()).get().value());
        if (!Strings.isNotBlank(gpsWaybillModificationDTO.getCarColor())) {
            gpsWaybillModificationDTO.setCarColor(GpsCarColorEnum.其它.value());
        }
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        R<String> value = dictClient.getValue(DictCodeConstant.THIRD_INTERFACE, GPS_SAVE_AND_ORDER, DEFAULT_TENANT_ID);
        String url = value.getData();
        if (Strings.isBlank(url)) {
            CommonException.throwCommonException("未维护三方接口");
        }
        String body = JSON.toJSONString(gpsWaybillModificationDTO, config);
        body = JSONUtil.toJsonPrettyStr(JsonUtil.parse(body, Object.class));
        String response = HttpUtils.gpsTask(url, Method.POST, new LinkedHashMap<>(), null, null, body, url);
        log.info(response);
        GPSData gpsData = JSONUtil.toBean(response, GPSData.class);
        if (!gpsData.getStatus().equals(20000)) {
            CommonException.throwCommonException(gpsData.getMsg());
        }
    }

    /**
     * @param gpsSignDTO:
     * @return void
     * @author yr
     * @description 签收签发
     * @date 2022/5/5 18:29
     */
    public void sign(GpsSignDTO gpsSignDTO) {
        TMTransportOrder tmTransportOrder = transportOrderService.lambdaQuery().eq(TMTransportOrder::getTransportNo, gpsSignDTO.getConsigNo()).one();
        if (tmTransportOrder != null) {
            String pushTag = tmTransportOrder.getPushTag();
            if (pushTag.equals("0")) {
                return;
            }
        }
        gpsSignDTO.setSignImg(picURL(gpsSignDTO.getSignImg()));
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        String url = dictClient.getValue(DictCodeConstant.THIRD_INTERFACE, DictCodeConstant.SIGN, DEFAULT_TENANT_ID).getData();
        if (Strings.isBlank(url)) {
            CommonException.throwCommonException("未维护三方接口");
        }
        String body = JSON.toJSONString(gpsSignDTO, config);
        body = JSONUtil.toJsonPrettyStr(JsonUtil.parse(body, Object.class));
        String response = HttpUtils.gpsTask(url, Method.POST, new LinkedHashMap<>(), null, null, body, url);
        log.info(response);
        GPSData gpsData = JSONUtil.toBean(response, GPSData.class);
        if (!gpsData.getStatus().equals(20000)) {
            CommonException.throwCommonException(gpsData.getMsg());
        }
    }

    //图片url拼接
    private String picURL(String url) {
        if (Strings.isNotBlank(url)) {
            return dictClient.getValue(DictCodeConstant.THIRD_INTERFACE, DictCodeConstant.URL, DEFAULT_TENANT_ID).getData() + url;
        } else {
            return url;
        }
    }
}
